package com.car.action.admin;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import com.alibaba.fastjson.JSONObject;
import com.car.common.model.Card;
import com.car.common.model.CardDiscuss;
import com.car.common.model.Message;
import com.car.common.model.UserFans;
import com.car.common.model.UserFriends;
import com.car.common.model.UserHellos;
import com.car.common.model.UserSees;
import com.car.common.model.Users;
import com.car.common.model.UsersInfo;
import com.car.common.model.VipRecord;
import com.car.intercept.AdminInterceptor;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.jfinal.aop.Before;
import com.jfinal.core.Controller;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.ehcache.CacheKit;
import com.utils.APIJSON;
import com.utils.CookiesUtil;
import com.utils.DateUtil;
import com.utils.RongCloudUtil;
import com.utils.StringUtil;
import com.utils.SystemClock;
import com.vdurmont.emoji.EmojiParser;

public class MessageController extends Controller {

	
	public void index_json() {
		getResponse().setHeader("Access-Control-Allow-Origin", "*");
		Map<String,Object> result = Maps.newHashMap();
		String andSql = "select m.* , FROM_UNIXTIME(m.msgTimestamp/1000,'%Y-%m-%d %H:%i') as create_time_string,u.nick_name,u.user_header from message as m LEFT JOIN users as u on m.toUserId = u.id where m.admin = 1 and  m.objectName = 'RC:TxtMsg' and m.channelType = 'PERSON'  and m.version =0 ";
		Message one = Message.dao.findFirst(andSql + " ORDER BY m.msgTimestamp asc ,m.id asc  limit 1 ");
		if (one != null) {
			Users send     =  Users.dao.findById(one.getStr("fromUserId"));
			Users receive  =  Users.dao.findById(one.getStr("toUserId"));
			result.put("send",     send);
			result.put("receive",  receive);
			result.put("viptime", DateUtil.commonDateFormat.format(new Date(send.getVipEndTime()*1000L)));
			
			VipRecord total = VipRecord.dao.findFirst("select sum(hot) as hot from vip_record where user_id = " + one.getStr("fromUserId") + " and target_user_id = " + one.getStr("toUserId"));
			
			String info =  " 距离:" + UsersInfo.dao.get_user_distance(Integer.valueOf(one.getStr("fromUserId")), Integer.valueOf(one.getStr("toUserId")));
			
			int vip_badpe = send.getInt("vip_badpe");
			int times = 0 ;
			if (vip_badpe == 0) {
				times = 5;
			} else if (vip_badpe == 1) {
				times = 30;
			} else if (vip_badpe == 2) {
				times = 30;
			} else if (vip_badpe == 3) {
				times = 5000;
			} else if (vip_badpe == 4) {
				times = 10000;
			}
			UserHellos todayUsedCnt = UserHellos.dao.findFirst("select count(id) as cnt from user_hellos where user_id = " + send.getId() +" and FROM_UNIXTIME(create_time, '%Y-%m-%d') = '" + DateUtil.commonDateFormat.format(new Date()) + "' and hot = 0 ");
			info += " 今天剩次数" + (times - todayUsedCnt.getLong("cnt").intValue());
			
			if (total != null ) {
				result.put("hot", total.getBigDecimal("hot") == null ? ("0 热度" + info):(total.getBigDecimal("hot") + " 热度 " + info));
			} else {
				result.put("hot", "0 热度 " + result);
			}
			// and m.version =0 
			List<Message> messageList = Message.dao.find("select m.* , FROM_UNIXTIME(m.msgTimestamp/1000,'%Y-%m-%d %H:%i') as create_time_string,u.nick_name,u.user_header from message as m LEFT JOIN users as u on m.toUserId = u.id where m.objectName = 'RC:TxtMsg' and m.channelType = 'PERSON'   and (m.fromUserId = "+one.get("fromUserId") + " or m.fromUserId = "+one.get("toUserId")+" ) and (m.toUserId = "+ one.get("toUserId") + " or m.toUserId = "+ one.get("fromUserId") +")  ORDER BY m.msgTimestamp asc ,m.id asc");
			for(Message m : messageList) {
				JSONObject contentJSON = JSONObject.parseObject(m.getStr("content"));
				m.set("content", contentJSON.getString("content"));
			}
			result.put("list", messageList);
			
			UserHellos total_hellos = UserHellos.dao.findFirst("select count(h.id) as total from user_hellos as h where h.user_id = " +  send.getId());
			
			UserHellos total_pass_hellos = UserHellos.dao.findFirst("select count(h.id) as total from user_hellos as h where h.user_id = " +  send.getId() +"  and status = 1 ");
			
			result.put("detail", String.format("申请好友此时:共%s 过%s", total_hellos.get("total"),total_pass_hellos.get("total")));
			
			String andSQL = "  (user_id = "+ send.getId() +" or target_user_id = " + send.getId() +") and status = 1 and delete_time is null order by id desc ";
			List<UserFriends> friends = UserFriends.dao.find("select * from user_friends where " + andSQL);
			ArrayList<Map<String,Object>> friends_result = Lists.newArrayList();
			for(UserFriends one_f : friends) {
				int userid = one_f.getUserId();
				int target_userid = one_f.getTargetUserId();
				int uid = userid;
				if (send.getId().intValue() == userid) {
					uid = target_userid;
				}
				
				String sql = "select u.*,ae.name as area_name, FROM_UNIXTIME(u.birthday,'%Y年%m月%d日') as birthday_string,u.is_true, CASE u.sex  WHEN '1' THEN '男' WHEN '2' THEN '女' WHEN '3' THEN 'CD' WHEN '4' THEN 'FtM' WHEN '5' THEN 'MtF'  ELSE '其他' END as sex_name ";
				sql += ", FROM_UNIXTIME(u.create_time,'%Y-%m-%d %H:%i') as create_time_string , FROM_UNIXTIME(u.vip_end_time,'%Y-%m-%d') as vip_end_time_string,u.auth_badge,u.talk_badge,u.vip_badpe,u.consume_badpe,u.credit  from users as u left join area ae on ae.code = u.area_id where u.id = " + uid;
				
				Users users = Users.dao.findFirst(sql);
				Map<String,Object> temp = Maps.newHashMap();
				temp.put("user_id", uid);
				temp.put("sex", users.get("sex_name"));
				temp.put("nick_name", StringUtil.decode(users.getNickName()));
				temp.put("area", users.get("area_name"));
				
				UserHellos hellos = UserHellos.dao.findFirst("select content from user_hellos where user_id = " + userid +" and target_user_id = " + target_userid +" and status = 1 order by id desc limit 1 ");
				if (hellos != null) {
					temp.put("content", StringUtil.decode(hellos.getStr("content")));
				} else {
					temp.put("content", "数据已删除");
				}
				friends_result.add(temp);
			}
			result.put("friends",friends_result);
			
		}
		renderJson(result);
	}
	
	public void index() {
		String andSql = "select m.* , FROM_UNIXTIME(m.msgTimestamp/1000,'%Y-%m-%d %H:%i') as create_time_string,u.nick_name,u.user_header from message as m LEFT JOIN users as u on m.toUserId = u.id where m.admin = 1 and  m.objectName = 'RC:TxtMsg' and m.channelType = 'PERSON'  and m.version =0 ";
		if(!StringUtil.empty(getPara("person"))) {
    		if (!"100".equalsIgnoreCase(getPara("person"))) {
    			andSql += StringUtil.getSQLForPerson(getPara("person"));
    		}
    	}
		Message one = Message.dao.findFirst(andSql + " ORDER BY m.msgTimestamp asc ,m.id asc  limit 1 ");
		if (one != null) {
			Users send     =  Users.dao.findById(one.getStr("fromUserId"));
			Users receive  =  Users.dao.findById(one.getStr("toUserId"));
			setAttr("send",     send);
			setAttr("receive",  receive);
			
			setAttr("viptime", DateUtil.commonDateFormat.format(new Date(send.getVipEndTime()*1000L)));
			
			VipRecord total = VipRecord.dao.findFirst("select sum(hot) as hot from vip_record where user_id = " + one.getStr("fromUserId") + " and target_user_id = " + one.getStr("toUserId"));
			
			String result =  " 距离:" + UsersInfo.dao.get_user_distance(Integer.valueOf(one.getStr("fromUserId")), Integer.valueOf(one.getStr("toUserId")));
			
			int vip_badpe = send.getInt("vip_badpe");
			int times = 0 ;
			if (vip_badpe == 0) {
				times = 5;
			} else if (vip_badpe == 1) {
				times = 30;
			} else if (vip_badpe == 2) {
				times = 30;
			} else if (vip_badpe == 3) {
				times = 5000;
			} else if (vip_badpe == 4) {
				times = 10000;
			}
			UserHellos todayUsedCnt = UserHellos.dao.findFirst("select count(id) as cnt from user_hellos where user_id = " + send.getId() +" and FROM_UNIXTIME(create_time, '%Y-%m-%d') = '" + DateUtil.commonDateFormat.format(new Date()) + "' and hot = 0 ");
			result += " 今天剩次数" + (times - todayUsedCnt.getLong("cnt").intValue());
			
			if (total != null ) {
				setAttr("hot", total.getBigDecimal("hot") == null ? ("0 热度" + result):(total.getBigDecimal("hot") + " 热度 " + result));
			} else {
				setAttr("hot", "0 热度 " + result);
			}
			// and m.version =0 
			List<Message> messageList = Message.dao.find("select m.* , FROM_UNIXTIME(m.msgTimestamp/1000,'%Y-%m-%d %H:%i') as create_time_string,u.nick_name,u.user_header from message as m LEFT JOIN users as u on m.toUserId = u.id where m.objectName = 'RC:TxtMsg' and m.channelType = 'PERSON'   and (m.fromUserId = "+one.get("fromUserId") + " or m.fromUserId = "+one.get("toUserId")+" ) and (m.toUserId = "+ one.get("toUserId") + " or m.toUserId = "+ one.get("fromUserId") +")  ORDER BY m.msgTimestamp asc ,m.id asc");
			for(Message m : messageList) {
				JSONObject contentJSON = JSONObject.parseObject(m.getStr("content"));
				m.set("content", contentJSON.getString("content"));
			}
			setAttr("list", messageList);
			
			UserHellos total_hellos = UserHellos.dao.findFirst("select count(h.id) as total from user_hellos as h where h.user_id = " +  send.getId());
			
			UserHellos total_pass_hellos = UserHellos.dao.findFirst("select count(h.id) as total from user_hellos as h where h.user_id = " +  send.getId() +"  and status = 1 ");
			
			setAttr("detail", String.format("申请好友此时:共%s 过%s", total_hellos.get("total"),total_pass_hellos.get("total")));
			
			
			String andSQL = "  (user_id = "+ send.getId() +" or target_user_id = " + send.getId() +") and status = 1 and delete_time is null order by id desc ";
			List<UserFriends> friends = UserFriends.dao.find("select * from user_friends where " + andSQL);
			ArrayList<Map<String,Object>> friends_result = Lists.newArrayList();
			for(UserFriends one_f : friends) {
				int userid = one_f.getUserId();
				int target_userid = one_f.getTargetUserId();
				int uid = userid;
				if (send.getId().intValue() == userid) {
					uid = target_userid;
				}
				
				String sql = "select u.*,ae.name as area_name, FROM_UNIXTIME(u.birthday,'%Y年%m月%d日') as birthday_string,u.is_true, CASE u.sex  WHEN '1' THEN '男' WHEN '2' THEN '女' WHEN '3' THEN 'CD' WHEN '4' THEN 'FtM' WHEN '5' THEN 'MtF'  ELSE '其他' END as sex_name ";
				sql += ", FROM_UNIXTIME(u.create_time,'%Y-%m-%d %H:%i') as create_time_string , FROM_UNIXTIME(u.vip_end_time,'%Y-%m-%d') as vip_end_time_string,u.auth_badge,u.talk_badge,u.vip_badpe,u.consume_badpe,u.credit  from users as u left join area ae on ae.code = u.area_id where u.id = " + uid;
				
				Users users = Users.dao.findFirst(sql);
				Map<String,Object> temp = Maps.newHashMap();
				temp.put("user_id", uid);
				temp.put("sex", users.get("sex_name"));
				temp.put("nick_name", StringUtil.decode(users.getNickName()));
				temp.put("area", users.get("area_name"));
				
				UserHellos hellos = UserHellos.dao.findFirst("select content from user_hellos where user_id = " + userid +" and target_user_id = " + target_userid +" and status = 1 order by id desc limit 1 ");
				if (hellos != null) {
					temp.put("content", StringUtil.decode(hellos.getStr("content")));
				} else {
					temp.put("content", "数据已删除");
				}
				
				
				
				friends_result.add(temp);
			}
			
			setAttr("friends",friends_result);
			
		} 
		
		String person = getPara("person");
        if(StringUtil.empty(person)) {
        	 person = CookiesUtil.getName(getRequest(), "person");
        } else {
        	if ("100".equals(person)) {
        		CookiesUtil.add(getResponse(), "person", "0");
        	} else {
        		CookiesUtil.add(getResponse(), "person", person);
        	}
        	
        }
        setAttr("person", person);
		setAttr("one", one);
		render("index.html");
	} 
	
	public void detail() {
		String fromUserId = getPara("fromUserId");
		String toUserId = getPara("toUserId");
		
	}
	
	
	public void wx() {
		Message one = Message.dao.findFirst("select m.* , FROM_UNIXTIME(m.msgTimestamp/1000,'%Y-%m-%d %H:%i') as create_time_string,u.nick_name,u.user_header from message as m LEFT JOIN users as u on m.toUserId = u.id where m.admin = 1 and  m.objectName = 'RC:TxtMsg' and m.channelType = 'PERSON'  and m.version =0 ORDER BY m.msgTimestamp asc ,m.id asc  limit 1  ");
		if (one != null) {
			Users send     =  Users.dao.findById(one.getStr("fromUserId"));
			Users receive  =  Users.dao.findById(one.getStr("toUserId"));
			setAttr("send",     send);
			setAttr("receive",  receive);
			
			// and m.version =0  
			List<Message> messageList = Message.dao.find("select m.* , FROM_UNIXTIME(m.msgTimestamp/1000,'%Y-%m-%d %H:%i') as create_time_string,u.nick_name,u.user_header from message as m LEFT JOIN users as u on m.toUserId = u.id where m.objectName = 'RC:TxtMsg' and m.channelType = 'PERSON'  and m.fromUserId ="+ one.get("fromUserId") + " and m.toUserId = "+ one.get("toUserId") + "  ORDER BY m.msgTimestamp asc ,m.id asc");
			for(Message m : messageList) {
				JSONObject contentJSON = JSONObject.parseObject(m.getStr("content"));
				m.set("content", contentJSON.getString("content"));
			}
			setAttr("list", messageList);
		}
		setAttr("one", one);
		render("wx.html");
	}
	
	
	
	public void remove() {
		getResponse().setHeader("Access-Control-Allow-Origin", "*");
		Message one = Message.dao.findById(getPara("id"));
		//Db.update("update user_friends set status = 2 where user_id ='"+ one.get("fromUserId") + "' and target_user_id = '"+ one.get("toUserId")+"'");
		Db.delete("delete from user_friends where (user_id ='"+ one.getStr("fromUserId") + "' and target_user_id = '"+ one.getStr("toUserId")+"') or (target_user_id ='"+ one.get("fromUserId") + "' and user_id = '"+ one.getStr("toUserId")+"')");
		
		Map<String,String> params = Maps.newHashMap();
    	params.put("userId", String.valueOf(one.getStr("fromUserId")));
    	params.put("blackUserId", String.valueOf(one.getStr("toUserId")));
    	RongCloudUtil.post("http://api-cn.ronghub.com/user/blacklist/add.json", params);
    	
    	Map<String,String> params2 = Maps.newHashMap();
    	params2.put("blackUserId", String.valueOf(one.getStr("fromUserId")));
    	params2.put("userId", String.valueOf(one.getStr("toUserId")));
    	RongCloudUtil.post("http://api-cn.ronghub.com/user/blacklist/add.json", params2);
    	
		//System.out.println("update message set version = 1 where fromUserId ='"+ one.getStr("fromUserId") + "' and toUserId = '"+ one.getStr("toUserId")+"'");
		Db.update("update message set version = 1 where fromUserId ='"+ one.getStr("fromUserId") + "' and toUserId = '"+ one.getStr("toUserId")+"'");
		renderText("操作成功!");
	}
	
	
	public void reply() {
		getResponse().setHeader("Access-Control-Allow-Origin", "*");
		Message one1 = Message.dao.findById(getPara("id"));
//		System.out.println("update message set version = 1 where fromUserId ='"+ one.getStr("fromUserId") + "' and toUserId = '"+ one.getStr("toUserId")+"'");
		
		Db.update("update users set login_status = 0,logout_time = "+ (SystemClock.now()/1000L + 5*6*60L ) + "  where id = " + one1.getStr("fromUserId"));
		Db.update("update message set version = 1 where fromUserId ='"+ one1.getStr("fromUserId") + "' and toUserId = '"+ one1.getStr("toUserId")+"'");
		
		
		Map<String, String> params = Maps.newHashMap();
		params.put("userId",   		one1.getStr("fromUserId"));
		params.put("blackUserId",   one1.getStr("toUserId"));
		RongCloudUtil.post("http://api-cn.ronghub.com/user/blacklist/remove.json", params);
		
		params.put("userId",   		one1.getStr("toUserId"));
		params.put("blackUserId",   one1.getStr("fromUserId"));
		RongCloudUtil.post("http://api-cn.ronghub.com/user/blacklist/remove.json", params);
		
		RongCloudUtil.sendTxt(one1.getStr("toUserId"), one1.getStr("fromUserId"), getPara("content"));
		
		
		Message one = new Message();
		one.set("fromUserId", one1.getStr("toUserId"));
		one.set("toUserId", one1.getStr("fromUserId"));
		one.set("admin", 1);
		one.set("objectName", "RC:TxtMsg");
		one.set("content", "{\"content\":\"" +  getPara("content") +"\"}");
		one.set("channelType", "PERSON");
		one.set("msgTimestamp", SystemClock.now());
//		one.set("msgUID", UUID.randomUUID());
		one.set("sensitiveType", 0);
		one.set("source", "web");
		one.set("version", 1);
		try {
			one.save();
		}catch (Exception e) {
			e.printStackTrace();
		}
		renderText("操作成功!");
	}
	
	public void pass() {
		getResponse().setHeader("Access-Control-Allow-Origin", "*");
		Message one = Message.dao.findById(getPara("id"));
		Db.update("update message set version = -1 where fromUserId ='"+ one.getStr("fromUserId") + "' and toUserId = '"+ one.getStr("toUserId")+"'");
		renderText("操作成功!");
	}
	
	
	public void appoint() {
		Message one = Message.dao.findFirst("select m.* , FROM_UNIXTIME(m.msgTimestamp/1000,'%Y-%m-%d %H:%i') as create_time_string,u.nick_name,u.user_header from message as m LEFT JOIN users as u on m.toUserId = u.id where m.id="+getPara("id"));
		if (one != null) {
			JSONObject contentJSON = JSONObject.parseObject(one.getStr("content"));
			one.set("content", contentJSON.getString("content"));
			
			Users send = Users.dao.findById(one.getStr("fromUserId"));
			
			Users receive = Users.dao.findById(one.getStr("toUserId"));
			setAttr("send", send);
			setAttr("receive", receive);
		}
		setAttr("one", one);
		render("index.html");
	}
	
	public void get_info_json() {
		getResponse().setHeader("Access-Control-Allow-Origin", "*");
		String user_id = getPara("user_id");
		String cache_key = "user_info_"+ user_id;
	    Map<String,Object> result = CacheKit.get("api", cache_key);
	    if (result == null) {
	        result = Maps.newHashMap();
			result.put("card_num", Card.dao.findFirst("select count(id) as cnt from card where user_id = " + user_id).get("cnt"));
			result.put("card_discuss_num", CardDiscuss.dao.findFirst("select count(id) as cnt from card_discuss where user_id = " + user_id).get("cnt"));
			result.put("fans_num", UserFans.dao.findFirst("select count(id) as cnt from user_fans where user_id = " + user_id).get("cnt"));
			result.put("see_num", UserSees.dao.findFirst("select count(id) as cnt from user_sees where user_id = " + user_id).get("cnt"));
			result.put("consume", VipRecord.dao.findFirst("select SUM(price) as price from  vip_record where (buy_type = 'WxPay' or buy_type = 'AliPay' or buy_type = 'ApplePay') and `status` = 1 and user_id = " + user_id).get("price"));
			Users users = Users.dao.findById(user_id);
			if (users != null) {
				result.put("nick_name", StringUtil.decode(users.getNickName()));
				result.put("hot", users.getHotVal());
				if(users.getUpTime() != null) {
					result.put("last_time", DateUtil.commonDateTimeFormat.format(new Date(users.getUpTime() *1000L)));	
				} else {
					result.put("last_time","未知");
				}
			} else {
				result.put("nick_name", "未知");
				result.put("hot","未知");
				result.put("last_time","未知");
			}
			
			
	        CacheKit.put("api", cache_key, result);
	    }
		renderJson(result);
	}
	
}
